<template>
    <div
        class="seamless-scroll-page"
        @mouseenter="handleMouseEnter"
        @mouseleave="handleMouseLeave"
    >
        <div class="seamless-scroll-page-container" ref="scrollContainer">
            <slot />
        </div>
    </div>
</template>
<script setup>
import { ref, onBeforeUnmount, onUnmounted, watch } from "vue";

const props = defineProps({
    min: {
        type: Number,
        default: () => 5,
    },
    step: {
        type: Number,
        default: () => 1,
    },
});
let scrollContainer = ref(null);

// const animationFrame = ref(null)
let animationFrame = null;

onBeforeUnmount(() => {
    onStop();
});

onUnmounted(() => {
    onStop();
});

const handleMouseEnter = () => {
    onStop();
};

const handleMouseLeave = () => {
    onStart();
};

const onStart = () => {
    ListScroll();
    animationFrame = requestAnimationFrame(onStart);
};

const onStop = () => {
    animationFrame && cancelAnimationFrame(animationFrame);
};

const ListScroll = () => {
    let scrollDom = scrollContainer.value;
    // 判读组件是否渲染完成
    if (scrollDom.offsetHeight == 0) {
        scrollDom = scrollContainer.value;
    } else {
        // 如果列表数量过少不进行滚动
        if (scrollDom.children.length < props.min) return;
        // 组件进行滚动
        scrollDom.scrollTop += 1;
        // 判断是否滚动到底部
        if (
            scrollDom.scrollTop ==
            scrollDom.scrollHeight - scrollDom.clientHeight
        ) {
            // 获取组件第一个节点
            let first = scrollDom.children[0];
            // 删除节点
            scrollDom.removeChild(first);
            // 将该节点拼接到组件最后
            scrollDom.append(first);
        }
    }
};

watch(
    () => scrollContainer.value,
    (newVal) => {
        if (newVal?.children && newVal?.children.length) onStart();
        else onStop();
    },
    {
        deep: true,
        immediate: true,
    }
);
</script>
<style lang="less" scoped>
.seamless-scroll-page {
    height: 100%;
    &-container {
        width: 100%;
        height: 100%;
        overflow: hidden;
        &-item {
            padding: 12px 0;
        }
    }
}
</style>
